package com.example.elearning.weather;

import android.content.Context;

import com.google.gson.Gson;

import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class WeatherApiClient {

    private static final String API_KEY = "cMAt9ZXfIPT1kRC0p9Z72mZvh5ePdH9k";
    private static WeatherApiClient instance;
    private WeatherApiClient() {
    }
    public static WeatherApiClient getInstance() {
        if (instance == null) {
            instance = new WeatherApiClient();
        }
        return instance;
    }
   public List<WeatherInfo> getInfoFromJson(Context context){
        List<WeatherInfo> weatherInfos = new ArrayList<>();
       try {
           /*
           改写的是字符串类型的变量
           String city = URLEncoder.encode("北京", "UTF-8");
           String url = "https://api.map.baidu.com/weather/v1/?location=CITY&output=json&ak=" + API_KEY;
           url = url.replace("CITY", city);
            */
           //改写的是int型的变量
           int cityCode = 222405; // 你的城市代码
           String district_id = String.valueOf(cityCode);
           String url = "https://api.map.baidu.com/weather/v1/?district_id=" + district_id + "&output=json&ak=" + API_KEY;
           //调用一个发送http请求的方法sendGet方法
           //发送请求后就得到了json字符串
           String jsonStr = sendGet(url);
            //创建Gson对象
           Gson gson = new Gson();
           // 创建一个TypeToken的匿名子类对象，并调用该对象的getType()方法
           Type listType = new TypeToken<List<WeatherInfo>>() {
           }.getType();
           // 把获取到的信息集合存到infoList中
           List<WeatherInfo> infoList = gson.fromJson(jsonStr, listType);
           return infoList;

       } catch (IOException e) {
           e.printStackTrace();
       }
       return weatherInfos;
   }

    public static String sendGet(String url) throws IOException {
        HttpURLConnection connection = null;

        BufferedReader reader = null;

        StringBuilder response = new StringBuilder();

        try {
            URL requestUrl = new URL(url);

            connection = (HttpURLConnection) requestUrl.openConnection();

            connection.setRequestMethod("GET");

            connection.connect();

            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (reader != null) {
                reader.close();
            }
        }

        return response.toString();
    }

}




